import { loadSprite } from "./helper/Loader";
import storage from './helper/DATA/localstorage'
import { setHomeBtn } from './helper/UI/StaticNode'
const { ccclass, property } = cc._decorator;

@ccclass
export default class LetterGame extends cc.Component {
    level: string = '1' // 关卡登记
    questionBank = [] // 题库
    answerGroup = []  // 当前题目所有答案
    answerOption = [] // 备选字母
    dataDict = {}
    points = null
    group = null
    lineWidth = 0
    strokeColor = null
    time = null
    duration = null
    pathArray = []
    path = null
    // levelInfo = {
    //     num: '1'
    // }

    // LIFE-CYCLE CALLBACKS:

    onLoad() {
        setHomeBtn(this)
        this.initGame()
        // 
        this.lineWidth = 5;
        this.strokeColor = cc.color(0, 0, 0);
        // this.isClearMode = false;
        this.group = this.addComponent('R.group');
        this.time = 3.0;
        this.duration = 1.0;
        this.pathArray = [];
    }

    // update (dt) {}
    start() {
        cc.log('start', this)
        this.eventRegister()
    }
    update(dt) {

        // 时间递增
        this.time += dt;

        // 设置显示比例
        let percent = this.time / this.duration;

        // 显示比例超过1 更新到队列中的下一条线
        if (percent > 1) {

            // 假如队列有path，排除没画线时出错
            if (this.pathArray.length > 0) {

                // 假如是清屏命令 直接清屏退出此次update
                if (this.pathArray[0].dataEvent === 'clear') {

                    this.clearAll();
                    this.pathArray.shift();
                    return;
                }

                // 比较是否是当前path，是的话移除
                if (this.path === this.pathArray[0].path) {

                    this.pathArray.shift();
                }
            }

            // 在移除之后（或者第一次） 判断队列还有没有path，有的话继续画
            if (this.pathArray.length > 0) {

                // 假如是清屏命令 直接清屏退出此次update
                if (this.pathArray[0].dataEvent === 'clear') {

                    this.clearAll();
                    this.pathArray.shift();
                    return;
                }

                // 开始新一条线的显示（初始化）
                this.path = this.pathArray[0].path;
                this.pathLength = this.path.getTotalLength();
                this.time = 0;
                this.duration = this.pathArray[0].duration;
                percent = 0;
            }
            return;
        }

        // 根据时间刷新画笔的显示
        this.path.dashOffset = this.pathLength * (1 - percent);
        this.path._dirty = true;
    }
    /**
     * @description  初始化游戏信息，包括关卡、题库、当前题目
     * @author 刘建文
     * @date 2019-12-23
     * @memberof LetterGame
     */
    async initGame() {
        this.level = storage.get('letter_level') || '1'
        const { json: questionBank } = await loadSprite('data/questionBank', cc.JsonAsset)
        this.questionBank = questionBank
        this.loadQuestion(this.level)
    }
    /**
     * @description     加载当前题目  
     * @author 刘建文
     * @date 2019-12-23
     * @param {string} [level='1']  当前关卡等级
     * @memberof LetterGame
     */
    loadQuestion(level = '1') {
        this.answerGroup = this.questionBank.filter(e => {
            return e.level === level
        }).reduce((a, b) => a.concat([b.data.trim()]), [])

        this.answerOption = Array.from(new Set(this.answerGroup.reduce((a, b) => a.concat(...b.split('')), [])))

        if (this.answerGroup.length !== 0) {
            storage.set('letter_level', level)
        }
    }
    eventRegister() {
        this.node.on(cc.Node.EventType.TOUCH_START, this.touch_start, this)
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this.touch_start, this)
        this.node.on(cc.Node.EventType.TOUCH_END, this.touch_start, this)
    }
    startDraw(dataDict) {
        // 判断是否是清屏
        if (dataDict.dataEvent === 'clear') {

            this.pathArray.push(dataDict);
            return;
        }

        // 初始化线
        let path = this.group.addPath();
        path.strokeColor = cc.color(0, 0, 0).fromHEX(dataDict.strokeColor);
        path.lineWidth = dataDict.lineWidth;
        path.fillColor = 'none';

        // 映射还原点
        var pathPoints = dataDict.points;
        var userPoints = [];
        for (var i = 0; i < pathPoints.length; i++) {

            let pointDict = pathPoints[i];
            var point = cc.p(pointDict.x * this.node.width, pointDict.y * this.node.height);
            userPoints.push(point);
        }

        // 画线并隐藏
        path.points(userPoints.reverse())
        var pathLength = path.getTotalLength();
        path.dashOffset = pathLength;
        path.dashArray = [pathLength];

        // 设置path字典
        var pathDict = {};
        pathDict.path = path;
        pathDict.duration = (dataDict.endTime - dataDict.startTime) / 1000.0;

        // 将path字典存入数组       
        this.pathArray.push(pathDict);
    }
    touch_start(touch, event) {
        cc.log('start', event)
        // 初始一条线的数据
        this.dataDict = {};
        this.dataDict.dataEvent = 'draw';

        // 获取开始时间点
        this.dataDict.startTime = new Date().getTime();

        // 获取触摸点数据
        var touchLoc = touch.getLocation();
        touchLoc = this.node.parent.convertToNodeSpaceAR(touchLoc);

        // 从group获取一条Path实例
        var path = this.group.addPath();
        path.fillColor = 'none';

        // // 判断是否是橡皮擦状态
        // if (this.isClearMode) {

        //     path.lineWidth = 15;
        //     path.strokeColor = cc.color(255, 255, 255);
        // } else {

        //     path.lineWidth = this.lineWidth;
        //     path.strokeColor = this.strokeColor;
        // }
        path.lineWidth = this.lineWidth;
        path.strokeColor = this.strokeColor;
        this.dataDict.strokeColor = path.strokeColor.toHEX("#rrggbb");
        this.dataDict.lineWidth = path.lineWidth;

        // 初始化点数组，并赋值开始位置的点
        this.points = [touchLoc];

        return true;
    }
    touch_move(touch, event) {
        cc.log('move', event)
        // 获取触摸点数据
        var touchLoc = touch.getLocation();
        touchLoc = this.node.parent.convertToNodeSpaceAR(touchLoc);

        // 添加到点数组内
        this.points.push(touchLoc);

        // 获取当前画的path实例，并更新内部展现点数据
        var path = this.group.children[this.group.children.length - 1];
        path.points(this.points);
    }
    touch_end() {
        cc.log('end', event)
        // 获取触摸点数据
        var path = this.group.children[this.group.children.length - 1];
        path.points(this.points);

        // 获取结束时间点
        this.dataDict.endTime = new Date().getTime();

        // 将点数组转化为相对于node宽高的映射位置
        this.pointDicts = [];
        for (var i = 0; i < this.points.length; i++) {

            let point = this.points[i];
            var pointDict = {};
            pointDict.x = point.x / this.node.width;
            pointDict.y = point.y / this.node.height;
            this.pointDicts.push(pointDict);
        }
        this.dataDict.points = this.pointDicts;

        let sendData = this.dataDict;

        // 本地测试同步数据
        // this.lookDraw.startDraw(sendData);

        // 网络同步数据
        // if (window.room_user) {

        //     var drawAction = gameAction.getDrawDataAction(window.room_user, sendData)
        //     happySocket.sendData(drawAction)

        // }
    }

}
